/**
 * add_new_nodes.java
 * ************************** 
 * @date May 30, 2011
 * @author Michele Tamburini
 * 
 * **************************
 */
package infrastructureAPI.scripts.instanceTools;

import infrastructureAPI.ResponseException;
import infrastructureAPI.APIMessages.ResponseMessage;
import infrastructureAPI.algorithms.instanceTools.AddNewNodes;
import infrastructureAPI.backendGate.APIRoutineFunctions;
import infrastructureAPI.backendGate.APIScript;
import infrastructureAPI.backendGate.GeneralScript;

import java.util.List;

/**
 * Description: 
 *
 */
public class add_new_nodes extends GeneralScript {
	
	protected AddNewNodes addNewNodesInstace = new AddNewNodes(null);
	
	protected String subcloud_id;
	protected int number_of_nodes;
	
	protected int mandatoryParametersIndex;

	/**
	 * @param args
	 */
	public add_new_nodes(String[] args) {
		super(args);
	}

	@Override
	public void checkNotGeneralOptionalParameters() {
		// nothing to do. This script may accept 
		// any but the shared optional parameters.
	}

	@Override
	public void composeMandatoryParameters() {
		mandatoryParametersIndex = optionalParameterIndex;
		subcloud_id = arguments.get(mandatoryParametersIndex);
		Integer temp_nodes = new Integer(arguments.get((++mandatoryParametersIndex)));
		number_of_nodes = temp_nodes.intValue();
	}

	@Override
	public APIScript instantiateAPIScript() {
		return new AddNewNodes(requester, subcloud_id, number_of_nodes);
	}

	@Override
	public boolean verifyMandatoryParameters() {
		boolean ret = true;
		int parameters = APIRoutineFunctions.extractParametersNumber(arguments);
		addNewNodesInstace = new AddNewNodes();
		int requiredMandatoryParameters = addNewNodesInstace.mandatoryParametersNumber();
		if(parameters != requiredMandatoryParameters){
			System.out.println(addNewNodesInstace.showUsage());
			ret = false;
		}
		return ret;
	}

	@Override
	public void waitingIncomingResposes() {
		// the first response means that a node collected the request
		ResponseMessage firstAnswer = waitingOneIncomingResponse();
		System.out.println("Response of request submission returning from "+
				firstAnswer.getSender());
		
		try {
			Object resp = firstAnswer.getAPIResponse().getResponse();
			System.out.println("Requeste correctly started submitted "+resp);
			System.out.println("Added new nodes to subcloud "+subcloud_id);
			List<ResponseMessage> responses = waitingIncomingResponses(number_of_nodes);
			for(ResponseMessage msg : responses){
				try {
					msg.getAPIResponse().getResponse();
					System.out.println(">"+msg.getSender());
				} catch (ResponseException e) {
					e.printStackTrace();
				}
			}
		} catch (ResponseException e1) {
			e1.printStackTrace();
		}
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		add_new_nodes instance = new add_new_nodes(args);
	}

}
